package com.example.demo.controller.train;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.base.config.auth.UserInfoShareHolder;
import com.example.demo.base.login.dto.UserCache;
import com.example.demo.domain.entity.TrainClass;
import com.example.demo.domain.entity.TrainClassUser;
import com.example.demo.domain.entity.TrainCommitRecord;
import com.example.demo.domain.entity.TrainHomework;
import com.example.demo.domain.entity.TrainHomeworkProblem;
import com.example.demo.domain.entity.User;
import com.example.demo.domain.vo.HomeWorkDetailVo;
import com.example.demo.domain.vo.ProblemScore;
import com.example.demo.domain.vo.RepetitionResult;
import com.example.demo.dto.ResponseDto;
import com.example.demo.enums.TrainSubmitStatus;
import com.example.demo.message.business.AbstractDataProcessBase;
import com.example.demo.message.business.BusinessProcessDataFactory;
import com.example.demo.service.TrainClassService;
import com.example.demo.service.TrainClassUserService;
import com.example.demo.service.TrainCommitRecordService;
import com.example.demo.service.TrainHomeworkProblemService;
import com.example.demo.service.TrainHomeworkService;
import com.example.demo.service.TrainReportService;
import com.example.demo.service.UserService;
import com.example.demo.tool.RepetitionRate;
import com.example.demo.tool.TimeStamp2Date;
import com.example.demo.utils.BeanCopyUtil;
import com.example.demo.utils.CommonUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.ss.formula.functions.T;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 报告模块
 * @author liguang03
 * @date 2024/4/6
 */
@Controller
@Slf4j
@RequestMapping("/train/train-class/report")
public class TrainClassReportController {


    @Resource
    private TrainHomeworkService trainHomeworkService;


    @Resource
    private TrainCommitRecordService trainCommitRecordService;

    @Resource
    private TrainHomeworkProblemService trainHomeworkProblemService;


    @Resource
    private UserService userService;

    @Resource
    private TrainClassUserService trainClassUserService;

    @Resource
    private TrainClassService trainClassService;


    @Resource
    private TrainReportService reportService;


    /**
     * 下载某班级指定作业成绩
     * @return
     */
    @RequestMapping("/download/user-report")
    @ResponseBody
    public ResponseDto userReport(@RequestParam("homeworkId") List<Long> homeworkId, Long classId,  HttpServletResponse response) {
        UserCache userInfo = UserInfoShareHolder.getUserInfo();
        if (userInfo == null) {
            return new ResponseDto<>().buildFail("未登录");
        }
        if (CollectionUtils.isEmpty(homeworkId) || CommonUtil.isNullId(classId)) {
            return new ResponseDto().buildFail("参数错误");
        }
        TrainClass trainClass = trainClassService.getById(classId);
        if (trainClass == null) {
            return new ResponseDto().buildFail("班级不存在");
        }
        List<TrainClassUser> allUserByClassId = trainClassUserService.getAllUserByClassId(classId);
        if (CollectionUtils.isEmpty(allUserByClassId)) {
            return new ResponseDto().buildFail("该班级无学生");
        }
        try {
            List<TrainHomeworkProblem> trainHomeworkProblems = trainHomeworkProblemService.queryByHwIds(homeworkId);

            //后续再移动代码
            List<ExcelExportEntity> colList = new ArrayList<ExcelExportEntity>();
            ExcelExportEntity colEntity = new ExcelExportEntity("学号", "userId");
            colEntity.setNeedMerge(true);
            colEntity.setWidth(30);
            colList.add(colEntity);
            colEntity = new ExcelExportEntity("姓名", "userName");
            colEntity.setNeedMerge(true);
            colEntity.setWidth(30);
            colList.add(colEntity);
            ExcelExportEntity deliColGroup = new ExcelExportEntity("每题得分", "scoreDetail");
            List<ExcelExportEntity> deliColList = new ArrayList<ExcelExportEntity>();
            for (int i = 0; i < trainHomeworkProblems.size(); i++) {
                String name = (trainHomeworkProblems.get(i).getProblemId()) + "题";
                String questionScore = "questionScore" + (i + 1);
                deliColList.add(new ExcelExportEntity(name, questionScore));
                deliColGroup.setList(deliColList);
            }
            colList.add(deliColGroup);

            List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
            for (TrainClassUser trainClassUser : allUserByClassId) {
                Map<String, Object> valMap = new HashMap<String, Object>();

                valMap.put("userId", trainClassUser.getUserId());
                valMap.put("userName", trainClassUser.getRealName());

                //根据id获取每题得分数
                List<ProblemScore> problemScores = new ArrayList<>();
                for (TrainHomeworkProblem trainHomeworkProblem : trainHomeworkProblems) {
                    ProblemScore temp = new ProblemScore();
                    List<TrainCommitRecord> trainCommitRecords = trainCommitRecordService.queryByHwIdAndPIdAndClassIdAndUser(trainHomeworkProblem.getHomeworkId(), trainHomeworkProblem.getProblemId(), classId, trainClassUser.getUserId());
                    List<TrainCommitRecord> collect = trainCommitRecords.stream().filter(trainCommitRecord -> CommonUtil.isNotNullId(trainCommitRecord.getSubmitId())).collect(Collectors.toList());
                    collect.sort(Comparator.comparing(TrainCommitRecord::getSubmitTime, Comparator.reverseOrder()));
                    temp.setProblemId(trainHomeworkProblem.getProblemId());
                    if (CollectionUtils.isEmpty(collect)) {
                        temp.setScore(0);
                    } else {
                        TrainCommitRecord record = collect.get(0);
                        temp.setScore(record.getScore());
                    }
                    problemScores.add(temp);
                }
                List<Map<String, Object>> deliDetailList = new ArrayList<Map<String, Object>>();
                Map<String, Object> deliValMap = new HashMap<String, Object>();
                for (int j = 0; j < problemScores.size(); j++) {
                    String tempQuestionScore = "questionScore" + (j % trainHomeworkProblems.size() + 1);
                    deliValMap.put(tempQuestionScore, " " + problemScores.get(j).getScore());
                }
                deliDetailList.add(deliValMap);
                valMap.put("scoreDetail", deliDetailList);

                list.add(valMap);
            }
            String className = trainClass.getName();
            response.setHeader("content-Type", "application/vnd.ms-excel");
            // 下载文件的默认名称(设置下载文件的默认名称)
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(className.getBytes("gb2312"), "iso8859-1") + ".xls");

            //导出操作
            try {
                Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(className + "成绩列表", "1"), colList, list);
                workbook.write(response.getOutputStream());
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new ResponseDto().buildSucceed();
    }


    /**
     * 下载查重报告
     * @param classId
     * @param homeworkId
     * @param response
     * @throws Exception
     */
    @RequestMapping("/downloadRepCheckReport")
    public void downloadRepCheckReport(Long classId, Long homeworkId,
                                       HttpServletResponse response) throws Exception {
        UserCache userInfo = UserInfoShareHolder.getUserInfo();
        if (userInfo == null || CommonUtil.isNullId(classId) || CommonUtil.isNullId(homeworkId)) {
            return ;
        }
        TrainClass trainClass = trainClassService.getById(classId);
        if (trainClass == null || !userInfo.getCompanyId().equals(trainClass.getCompanyId())) {
            return ;
        }
        List<TrainHomeworkProblem> trainHomeworkProblems = trainHomeworkProblemService.queryByHwId(homeworkId);
        if (CollectionUtils.isEmpty(trainHomeworkProblems)){
            return ;
        }
        reportService.downloadRepCheckReport(trainClass, trainHomeworkProblems.get(0) ,response);
    }



}
